package com.leetcode.easy;

import com.leetcode.entity.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author zfl
 * @Classname SolutionMaxDepth
 * @Description 计算二叉树最大深度
 * @Date 2020/9/2 16:32
 * @Created by zfl
 */
public class SolutionMaxDepth {

    /**
     * @param root
     * @return
     * 说明：计算一个树的深度可以先计算其左子树的深度和右子树的深度，进而递归
     * 执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
     * 内存消耗：39.8 MB, 在所有 Java 提交中击败了42.28%的用户
     */
    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }else {
            int leftHeght = maxDepth(root.left);
            int rightHeight = maxDepth(root.right);
            return Math.max(leftHeght, rightHeight) + 1;
        }
    }

    /**
     * @param root
     * @return
     * @description 广度优先搜索，每次遍历一整层
     */
    public int maxDepth2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }
        return ans;
    }
}
